package com.example.mydownloader

import android.annotation.SuppressLint
import android.content.Intent
import android.os.*
import android.widget.Button
import android.widget.ImageView
import androidx.appcompat.app.AppCompatActivity
import com.bumptech.glide.Glide
import com.bumptech.glide.request.RequestOptions
import com.example.mydownloader.mymodule.log.LogUtil
import com.example.mydownloader.ui.login.LoginActivity
import java.util.concurrent.TimeUnit

class LaunchActivity : AppCompatActivity() {

    private var mHandler = object : Handler(Looper.getMainLooper()) {
        @SuppressLint("SetTextI18n")
        override fun handleMessage(msg: Message) {
            when (msg.what) {
                MESSAGE_ADVERTISEMENT_COUNT_DOWN -> {
                    val text = btnAdvertisement.text.toString()
                    val seconds = text.substring(0, text.length - 1)
                    val second = seconds.toInt() - 1
                    if (second > 0) {
                        btnAdvertisement.text = "${second}s"
                        LogUtil.d("btnAdvertisement.text = ${btnAdvertisement.text}")
                        this.sendMessageDelayed(mMessage, TimeUnit.SECONDS.toMillis(1))
                    } else {
                        this.post {
                            startLoginActivity()
                        }
                    }
                }
            }
        }
    }


    private var mMessage = Message()
        get() {
            val m = Message()
            m.what = MESSAGE_ADVERTISEMENT_COUNT_DOWN
            field = m
            return field
        }

    companion object {
        private var MESSAGE_ADVERTISEMENT_COUNT_DOWN: Int = 1
    }

    private lateinit var imgAdvertisement: ImageView
    private lateinit var btnAdvertisement: Button

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_launch)
        btnAdvertisement = findViewById(R.id.btn_advertisement)
        btnAdvertisement.text = resources.getString(R.string.three_seconds)
        LogUtil.d("btnAdvertisement.text = ${btnAdvertisement.text}")
        btnAdvertisement.setOnClickListener {
            mHandler.post {
                startLoginActivity()
            }
        }
        mHandler.sendMessageDelayed(mMessage, TimeUnit.SECONDS.toMillis(1))
        imgAdvertisement = findViewById(R.id.image_advertisement)
        if (!this.isDestroyed) {
            Glide.with(this)
                .applyDefaultRequestOptions(RequestOptions.fitCenterTransform())
                .asGif()
                .load(R.drawable.launch)
                .into(imgAdvertisement)
        }
    }

    private fun startLoginActivity() {
        if (!this.isDestroyed) {
            startActivity(Intent(this@LaunchActivity, LoginActivity::class.java))
            Glide.with(this).clear(imgAdvertisement)
            this@LaunchActivity.finish()
        }
    }
}